package com.gouqi.tools.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gouqi.gouqitoolscommon.model.entity.Tool;
import com.gouqi.gouqitoolscommon.model.entity.UserTool;
import com.gouqi.tools.annotation.AuthCheck;
import com.gouqi.tools.common.BaseResponse;
import com.gouqi.tools.common.ErrorCode;
import com.gouqi.tools.common.ResultUtils;
import com.gouqi.tools.exception.BusinessException;
import com.gouqi.tools.mapper.UserToolMapper;
import com.gouqi.tools.model.vo.ToolVO;
import com.gouqi.tools.service.ToolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分析控制器
 */
@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {

    @Resource
    private UserToolMapper userToolMapper;

    @Resource
    private ToolService toolService;

    @GetMapping("/hot/tool/invoke")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<ToolVO>> listHotInvokeTool() {

        List<UserTool> userToolList = userToolMapper.listHotInvokeTool(3);
        // 使用stream快速获取到id
        Map<String, List<UserTool>> ToolMap = userToolList.stream().collect(Collectors.groupingBy(UserTool::getToolId));

        QueryWrapper<Tool> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ToolMap.keySet());
        List<Tool> list = toolService.list(queryWrapper);

        if (CollectionUtil.isEmpty(list)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }

        List<ToolVO> toolVOList = list.stream().map(tool -> {
            ToolVO toolVO = new ToolVO();
            BeanUtils.copyProperties(tool, toolVO);
            int totalNum = ToolMap.get(tool.getId()).get(0).getTotalNum();
            toolVO.setTotalNum(totalNum);
            return toolVO;
        }).collect(Collectors.toList());

        return ResultUtils.success(toolVOList);
    }
}
